//
//  SendViewController.m
//  OrderFood
//
//  Created by xiaofang wang on 2018/10/23.
//  Copyright © 2018年 zhiyuan. All rights reserved.
//  @"配送列表"

#import "SendViewController.h"
#import "OrderDetailViewController.h"
#import "AbnomalDetailViewController.h"
#import "SendCell.h"
#import "SendFooterView.h"
#import "HeadderView.h"
#import "SureSendView.h"
#import "BaseTabBarViewController.h"
#import "AppDelegate.h"
@interface SendViewController ()<UITableViewDelegate,UITableViewDataSource, SendCellDelegate>


@property (strong, nonatomic)NSMutableArray <OrderModel *> *dataSource;

@end

@implementation SendViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _dataSource = [NSMutableArray new];
    CGRect tableViewFrame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-SafeAreaTopHeight-TabBar_HEIGHT-MHTitilesViewH - SafeAreaBottomHeight);
    NSLog(@"%@",NSStringFromCGRect(tableViewFrame));
    
    [self loadTableViewWithFrame:tableViewFrame tableViewStyle:UITableViewStyleGrouped refreshStyle:LSRefreshTypeJustHeader];
    self.mytableview.delegate = self;
    self.mytableview.dataSource = self;
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self ls_headerBeginRefreshing];
}


- (void)requestNewData{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self netWorkSend];
    });
}


-(void)netWorkSend {

    WeakObj(self)
    [NetWork requestDeliveryListSuccessBlock:^(NSDictionary * _Nonnull response) {
        if (RES_SUCESS) {
            [weakself.dataSource removeAllObjects];
            for (NSDictionary *dic in [response objectForKey:@"data"]) {
                OrderModel *orderModel = [OrderModel new];
                [orderModel yy_modelSetWithJSON:dic];
                orderModel.orderId = [NSString stringWithFormat:@"%@", [dic objectForKey:@"id"]];
                [weakself.dataSource addObject:orderModel];
            }
            
            
            ////更新自己现在的位置
            [GetLocation getMoLocationWithSuccess:^(double lat, double lng) {
                [UserDefault setDouble:lat forKey:LAT_KEY];
                [UserDefault setDouble:lng forKey:LON_KEY];
                [weakself getTimeDistance];
                [weakself.mytableview reloadData];
            } Failure:^(NSError *error) {
            }];
            
        }else {
            [HUD showMessage:MESSAGE];
        }
        [self ls_headerEndRefreshing];
    } failBlock:^(NSString * _Nonnull message) {

        [HUD showMessage:FAIL_MESSAGE];
        [self ls_headerEndRefreshing];
    }];
}

-(void)getTimeDistance {
    //    NSString *orgin = [NSString stringWithFormat:@"%f,%f|%@,%@",LAT_VALUE, LON_VALUE, _orderModel.shop.latitude, _orderModel.shop.longitude];
    __block NSInteger count = 0;
    for (NSInteger index = 0; index < _dataSource.count; index ++) {
        OrderModel *orderModel = [_dataSource objectAtIndex:index];
        NSString *orgin = [NSString stringWithFormat:@"51.89373666666667,-8.43928|%@,%@", orderModel.shop.latitude, orderModel.shop.longitude];
        NSString *destions = [NSString stringWithFormat:@"%@,%@|%@,%@", orderModel.shop.latitude, orderModel.shop.longitude, orderModel.user.latitude, orderModel.user.longitude];
        WeakObj(self)
        [NetWork netWorkDistanceTime:orgin andDestination:destions success:^(NSDictionary * _Nonnull response) {
            if ([[response objectForKey:@"status"] isEqualToString:@"OK"]) {
                NSArray *data = [response objectForKey:@"rows"];
                if (data.count > 0) {
                    orderModel.str1 = [[[[[data objectAtIndex:0] objectForKey:@"elements"] objectAtIndex:0] objectForKey:@"distance"] objectForKey:@"text"];
                    orderModel.str2 = [NSString stringWithFormat:@"(%@)", [[[[[data objectAtIndex:0] objectForKey:@"elements"] objectAtIndex:0] objectForKey:@"duration"] objectForKey:@"text"]];
                    orderModel.str3 = [[[[[data objectAtIndex:1] objectForKey:@"elements"] objectAtIndex:1] objectForKey:@"distance"] objectForKey:@"text"];
                    orderModel.str4 = [NSString stringWithFormat:@"(%@)", [[[[[data objectAtIndex:1] objectForKey:@"elements"] objectAtIndex:1] objectForKey:@"duration"] objectForKey:@"text"]];
                    [weakself.dataSource replaceObjectAtIndex:index withObject:orderModel];
                    count+=1;
                    if (count == weakself.dataSource.count) {
                        [weakself.mytableview reloadData];
                    }
                    
                }
            }
        } failure:^(NSString * _Nonnull message) {
            
        }];
        
    }
    
    
}



#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellID = @"SendCellId";
    SendCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[SendCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.orderModel = [_dataSource objectAtIndex:indexPath.section];
    cell.deleateS = self;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    OrderDetailViewController *detailVC = [[OrderDetailViewController alloc] init];
    detailVC.orderState = SendState;
    detailVC.hidesBottomBarWhenPushed =YES;
    detailVC.orderModel = [_dataSource objectAtIndex:indexPath.section];
    [self.navigationController pushViewController:detailVC animated:YES];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 15;
}


-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.0001;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}




-(void)sureSend:(UIButton *)sender{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"detail_suresend", nil) message:NSLocalizedString(@"detail_whethersuresend", nil) preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"detail_cancel",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    WeakObj(self)
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"detail_sure",nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakself finishOrder];
    }];
    [alertVC addAction:cancelAction];
    [alertVC addAction:sureAction];
    [self presentViewController:alertVC animated:YES completion:nil];
}

-(void)finishOrder{
    SureSendView *sureView = [[SureSendView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) withTitle:NSLocalizedString(@"detail_orderFinish",nil)];
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    UIWindow *mainWindow = appDelegate.window;
    BaseTabBarViewController *tabBarVC = (BaseTabBarViewController *)mainWindow.rootViewController;
    [tabBarVC.view addSubview:sureView];
}

#pragma mark - SendCellDelegate

-(void)sendCellDidCall:(SendCell *)cell isUser:(BOOL)isUser {
    NSIndexPath *indexPath = [self.mytableview indexPathForCell:cell];
    if (isUser) {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"detail_callUser", nil) message:[NSString stringWithFormat:@"%@%@",NSLocalizedString(@"detail_call", nil),_dataSource[indexPath.section].user.phone] preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"detail_cancel",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"detail_sure",nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alertVC addAction:cancelAction];
        [alertVC addAction:sureAction];
        [self presentViewController:alertVC animated:YES completion:nil];
    }else {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"detail_callMerchant", nil) message:[NSString stringWithFormat:@"%@%@",NSLocalizedString(@"detail_call", nil),_dataSource[indexPath.section].shop.phone] preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"detail_cancel",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"detail_sure",nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alertVC addAction:cancelAction];
        [alertVC addAction:sureAction];
        [self presentViewController:alertVC animated:YES completion:nil];
    }
}

/**
 status
 如果status=0，则圈出的按钮显示为“开始配送”，status=1，则显示“确认送达”
 开始配送，接口：/rider/work/order/delivery/confirm
 确认送达，接口：/rider/work/order/finish
 */
-(void)sendCellDidOpreate:(SendCell *)cell isError:(BOOL)isError status:(NSNumber *)status{
    NSIndexPath *indexPath = [self.mytableview indexPathForCell:cell];
    
    
    //取出model
    OrderModel *currentModel = [_dataSource objectAtIndex:indexPath.section];
    
    if (isError) { //一：异常上报
        AbnomalDetailViewController *abDetailVC = [[AbnomalDetailViewController alloc] init];
        abDetailVC.orderModel = [_dataSource objectAtIndex:indexPath.section];
        [self.navigationController pushViewController:abDetailVC animated:YES];
    }else { //二：开始配送
        
        if ([currentModel.status isEqualToNumber:@0]) { //开始配送

            [self showAlertWithTitle:@"确定" message:@"是否确认配送?" sureActionBlock:^{
                [IndicatorManager showOperateBegin:@""];

                [NetWork requestSendStartWithOrderId:currentModel.orderId successBlock:^(NSDictionary * _Nonnull response) {
                    [IndicatorManager showOperateEnd];

                    if (RES_SUCESS) {
                        
                        [self requestNewData];//重新刷新
                    }else {
                        [IndicatorManager showMessage:MESSAGE];
                    }
                } failBlock:^(NSString * _Nonnull message) {
                    [IndicatorManager showOperateEnd];
                    [IndicatorManager showMessage:message];
                }];
            }];
            
        }else if([currentModel.status isEqualToNumber:@1]) { //确认送达
            [self showAlertWithTitle:@"确定" message:@"是否确认商品已送达?" sureActionBlock:^{
                
                [IndicatorManager showOperateBegin:@""];
                
                [NetWork requestSendEndWithOrderId:currentModel.orderId successBlock:^(NSDictionary * _Nonnull response) {
                    
                    [IndicatorManager showOperateEnd];
                    
                    [self requestNewData];//重新刷新
                } failBlock:^(NSString * _Nonnull message) {
                    [IndicatorManager showOperateEnd];
                    [IndicatorManager showMessage:message];
                }];
            }];
        }
    }
}

/**弹框*/
- (void)showAlertWithTitle:(NSString *)title message:(NSString *)message sureActionBlock:(void(^)(void))block {

//    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"detail_suresend", nil) message:NSLocalizedString(@"detail_whethersuresend", nil) preferredStyle:UIAlertControllerStyleAlert];
//    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"detail_cancel",nil) style:UIAlertActionStyleCancel handler:nil];
//
//    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"detail_sure",nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        if (block) {
//            block();
//        }
//    }];
//    [alertVC addAction:cancelAction];
//    [alertVC addAction:sureAction];
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"detail_sure",nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (block) {
            block();
        }
    }];
    [alertVC addAction:cancelAction];
    [alertVC addAction:sureAction];
    [self presentViewController:alertVC animated:YES completion:nil];
}

#pragma mark - 确认送达网络操作
-(void)netWorkFinshSendFood:(NSIndexPath *)indexPath {
    [HUD showOperateBegin:@""];
    NSString *orderId = _dataSource[indexPath.section].orderId;
    WeakObj(self)
    [NetWork netWorkSendFinish:orderId success:^(NSDictionary * _Nonnull response) {
        [HUD showOperateEnd];
        if (RES_SUCESS) {
            [HUD showMessage:@"操作成功"];
            [weakself.dataSource removeObjectAtIndex:indexPath.section];
            [weakself.mytableview deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationMiddle];
            [self finishOrder];
        }else {
            [HUD showMessage:MESSAGE];
        }
    } failure:^(NSString * _Nonnull message) {
        [HUD showOperateEnd];
    }];
}


#pragma mark - 网络请求
@end
